﻿using PRO.Data;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace PRO.Controls
{
    [ToolboxData("<{0}:DelControl runat=server></{0}:DelControl>")]
    public class DelControl : CompositeControl
    {
        #region 属性
        [CategoryAttribute("是否返回当前被删除的数据"),
        Bindable(true),
        DefaultValue(false),
        Description("是否返回当前被删除的数据"),
        Localizable(true)]
        public bool BackData
        {
            get
            {
                if (ViewState["Del_BackData"] == null || ViewState["Del_BackData"].ToString() == "")
                    return false;
                return Convert.ToBoolean(ViewState["Del_BackData"]);
            }
            set
            {
                ViewState["Del_BackData"] = value.ToString();
            }
        }


        [CategoryAttribute("删除设置"),
        Bindable(true),
        DefaultValue(true),
        Description("是否弹出删除提示对话框"),
        Localizable(true)]
        public bool DelConfirm
        {
            get
            {
                if (ViewState["DelConfirm"] == null || ViewState["DelConfirm"].ToString() == "")
                    return true;
                return Convert.ToBoolean(ViewState["DelConfirm"]);
            }
            set
            {
                ViewState["DelConfirm"] = value.ToString();
            }
        }
        [CategoryAttribute("删除设置"),
        Bindable(true),
        DefaultValue("您确定要删除吗？"),
        Description("删除提示框的提示内容"),
        Localizable(true)]
        public string AlertText
        {
            get
            {
                if (ViewState["AlertText"] == null || ViewState["AlertText"].ToString() == "")
                    return "您确定要删除吗？";
                return (String)ViewState["AlertText"];
            }
            set
            {
                ViewState["AlertText"] = value.ToString();
            }
        }
        [CategoryAttribute("删除设置"),
        Bindable(true),
        DefaultValue("删除"),
        Description("按钮文字"),
        Localizable(true)]
        public string Text
        {
            get
            {
                if (ViewState["Text"] == null || ViewState["Text"].ToString() == "")
                    return "删除";
                return (String)ViewState["Text"];
            }
            set
            {
                ViewState["Text"] = value.ToString();
            }
        }

        [CategoryAttribute("自定义参数"),
        Bindable(true),
        DefaultValue(""),
        Description("自定义参数"),
        Localizable(true)]
        public string Argument
        {
            get
            {
                if (ViewState["Del_Argument"] == null || ViewState["Del_Argument"].ToString() == "")
                    return "";
                return (String)ViewState["Del_Argument"];
            }
            set
            {
                ViewState["Del_Argument"] = value.ToString();
            }
        }


        [CategoryAttribute("删除设置"),
        Bindable(true),
        DefaultValue(""),
        Description("图片路径"),
        Localizable(true)]
        public string Icon
        {
            get
            {
                return (String)ViewState["Icon"];
            }
            set
            {
                ViewState["Icon"] = value.ToString();
            }
        }
        [CategoryAttribute("删除设置"),
        Bindable(true),
        DefaultValue(""),
        Description("操作的表名"),
        Localizable(true)]
        public string TableName
        {
            get
            {
                return (String)ViewState["Del_TableName"];
            }
            set
            {
                ViewState["Del_TableName"] = value.ToString();
            }
        }
        [CategoryAttribute("删除设置"),
        Bindable(true),
        DefaultValue(""),
        Description("操作表的主键列名"),
        Localizable(true)]
        public string KeyField
        {
            get
            {
                if (ViewState["Del_KeyField"] == null || (String)ViewState["Del_KeyField"] == "")
                    return "id";
                return (String)ViewState["Del_KeyField"];
            }
            set
            {
                ViewState["Del_KeyField"] = value.ToString();
            }
        }
        [CategoryAttribute("删除设置"),
        Bindable(true),
        DefaultValue(""),
        Description("排序时的过滤条件（sql语句），例如：type=5"),
        Localizable(true)]
        public string Filter
        {
            get
            {
                return (String)ViewState["Del_Filter"];
            }
            set
            {
                ViewState["Del_Filter"] = value.ToString();
            }
        }


        [CategoryAttribute("设置删除按钮样式"),
        Bindable(true),
        DefaultValue(DelStyleItems.Button),
        Description("设置删除按钮样式"),
        Localizable(true)]
        public DelStyleItems DelBtnStyle
        {
            get
            {
                if (ViewState["DelBtnStyle"] == null || ViewState["DelBtnStyle"].ToString() == "")
                    return DelStyleItems.Button;
                return (DelStyleItems)ViewState["DelBtnStyle"];
            }
            set
            {
                ViewState["DelBtnStyle"] = value;
            }
        }
        public enum DelStyleItems
        {
            Button = 0,
            Link = 1,
            Image = 2,
        }

        [CategoryAttribute("当前ID"),
        Bindable(true),
        DefaultValue(-1),
        Description("当前编号"),
        Localizable(true)]
        public int ItemID
        {
            get
            {
                if (ViewState["Sort_ItemID"] == null || (String)ViewState["Sort_ItemID"] == "")
                    return -1;
                return int.Parse(ViewState["Sort_ItemID"].ToString());
            }
            set
            {
                ViewState["Sort_ItemID"] = value.ToString();
            }
        }
        #endregion

        protected override void CreateChildControls()
        {
            if (this.ItemID == -1)
            {
                Label msg = new Label();
                msg.ForeColor = Color.Red;
                msg.Font.Size = 8;
                msg.Text = "必须指定ItemID（唯一编号）";
                Controls.Add(msg);
            }
            else if (string.IsNullOrWhiteSpace(this.TableName))
            {
                Label msg = new Label();
                msg.ForeColor = Color.Red;
                msg.Font.Size = 8;
                msg.Text = "必须指定TableName（需要操作的表名）";
                Controls.Add(msg);
            }
            else if (string.IsNullOrWhiteSpace(this.KeyField))
            {
                Label msg = new Label();
                msg.ForeColor = Color.Red;
                msg.Font.Size = 8;
                msg.Text = "必须指定KeyField（主键列名）";
                Controls.Add(msg);
            }
            else if (this.ItemID != -1 && !string.IsNullOrWhiteSpace(this.TableName) && !string.IsNullOrWhiteSpace(this.KeyField))
            {
                switch (this.DelBtnStyle.ToString())
                {
                    case "Button":
                        Button del_btn = new Button();
                        del_btn.Text = this.Text;
                        del_btn.Click += Del_Btn_Click;
                        del_btn.ID = "Del_Btn_BoundField";
                        if (this.DelConfirm)
                            del_btn.OnClientClick = "javascript:return confirm('" + this.AlertText + "');";
                        Controls.Add(del_btn);
                        break;
                    case "Link":
                        LinkButton del_link = new LinkButton();
                        del_link.ID = "Del_Link_BoundField";
                        del_link.Text = this.Text;
                        del_link.Click += Del_Link_Click;
                        if (this.DelConfirm)
                            del_link.OnClientClick = "javascript:return confirm('" + this.AlertText + "');";
                        Controls.Add(del_link);
                        break;
                    case "Image":
                        ImageButton del_image = new ImageButton();
                        del_image.ImageUrl = this.Icon;
                        del_image.ToolTip = this.Text;
                        del_image.Click += Del_Image_Click;
                        if (this.DelConfirm)
                            del_image.OnClientClick = "javascript:return confirm('" + this.AlertText + "');";
                        Controls.Add(del_image);
                        break;
                }
            }
            base.RecreateChildControls();
        }
        void Del_Btn_Click(object sender, EventArgs e)
        {
            Button cell = sender as Button;
            int key =this.ItemID;
            DataTable dt;
            if (this.BackData)
            {
                if (DelControlManager.Del(this.TableName, this.KeyField, key, this.Filter, out dt))
                {
                    DelCallBack_Event(this.Argument, dt);
                }
            }
            else
            {
                if (DelControlManager.Del(this.TableName, this.KeyField, key, this.Filter))
                {
                    DelCallBack_Event(this.Argument, null);
                }
            }
        }
        void Del_Link_Click(object sender, EventArgs e)
        {
            LinkButton cell = sender as LinkButton;
            int key = this.ItemID;
            DataTable dt;
            if (this.BackData)
            {
                if (DelControlManager.Del(this.TableName, this.KeyField, key, this.Filter, out dt))
                {
                    DelCallBack_Event(this.Argument, dt);
                }
            }
            else
            {
                if (DelControlManager.Del(this.TableName, this.KeyField, key, this.Filter))
                {
                    DelCallBack_Event(this.Argument, null);
                }
            }
        }
        void Del_Image_Click(object sender, EventArgs e)
        {
            ImageButton cell = sender as ImageButton;
            int key = this.ItemID;
            DataTable dt;
            if (this.BackData)
            {
                if (DelControlManager.Del(this.TableName, this.KeyField, key, this.Filter, out dt))
                {
                    DelCallBack_Event(this.Argument, dt);
                }
            }
            else
            {
                if (DelControlManager.Del(this.TableName, this.KeyField, key, this.Filter))
                {
                    DelCallBack_Event(this.Argument, null);
                }
            }
        }
        #region 自定义事件
        //定义委托
        public delegate void DelCallBackHandle(string Argument, DataTable del);
        //定义事件
        public event DelCallBackHandle DelCallBack;
        /// <summary>
        /// 删除回调
        /// </summary>
        /// <param name="keyvalue">当前删除的主键值</param>
        private void DelCallBack_Event(string Argument, DataTable del)
        {
            if (DelCallBack != null)
                DelCallBack(Argument, del);//自身作为参数传递
        }
        #endregion
    }
    public class DelControlManager
    {
        public static bool Del(string table, string key, int id, string filter,out DataTable del)
        {
            bool r = false;
            del = null;
            if (filter != null && filter.ToString() != "")
                filter = " and " + filter + " ";

            string sql_back = "select * from " + table + " where " + key + "=" + id + filter; ;
            del = DbHelper.ExecuteDataset(CommandType.Text, sql_back).Tables[0];

            string sql = "delete " + table + " where " + key + "=" + id + filter;
            r = Convert.ToBoolean(DbHelper.ExecuteNonQuery(CommandType.Text, sql));
            return r;
        }
        public static bool Del(string table, string key, int id, string filter)
        {
            bool r = false;
            if (filter != null && filter.ToString() != "")
                filter = " and " + filter + " ";
            string sql = "delete " + table + " where " + key + "=" + id + filter;
            r = Convert.ToBoolean(DbHelper.ExecuteNonQuery(CommandType.Text, sql));
            return r;
        }
    }
}
